import 'dart:async';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:flutter_app/utils/permission_utils.dart';
import 'package:flutter_app/values/CommonParam.dart';

/**
 * @Description: 高德地图工具类
 * @Author: 下雨了
 * @CreateDate: 2022-07-18 15:31
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-8-9 15:30
 * @UpdateRemark: 处理第一次无法获取信息
 * @Version: 1.1
 */
/// https://lbs.amap.com/api/flutter/guide/positioning-flutter-plug-in/interface-info

// 自定义回调信息
typedef LocationInfoCallback = void Function(LocationInfo locationInfo);

class AMapUtils {
  late AMapFlutterLocation location;
  late Completer<LocationInfo> completer;

  // 私有构造函数
  AMapUtils._internal() {
    location = AMapFlutterLocation();
    completer = Completer();
    Stream<Map<String, Object>> stream = onLocationChanged(location);
    stream.listen((Map<String, Object> result) {
      if (!result.containsKey('address')) {
        return;
      }
      double longitude = double.tryParse(result['longitude'].toString()) ?? 0;
      double latitude = double.tryParse(result['latitude'].toString()) ?? 0;
      String address = result['address'].toString();

      LocationInfo locationInfo = LocationInfo(longitude: longitude, latitude: latitude, address: address);

      if (!completer.isCompleted) {
        completer.complete(locationInfo);
      }

      stopLocation(location);
    });
  }

  // 保存单例
  static final AMapUtils _amapUtils = AMapUtils._internal();

  // 工厂构造函数
  factory AMapUtils() => _amapUtils;

  static void init() {
    updatePrivacyShow(true, true);
    updatePrivacyAgree(true);
  }

  /// 设置Android和iOS的apikey
  static void setApiKey() {
    AMapFlutterLocation.setApiKey(CommonParam.AMAP_ANDROID_APIKEY, CommonParam.AMAP_IOS_APIKEY);
  }

  /// 设置是否已经包含高德隐私政策并弹窗展示显示用户查看，如果未包含或者没有弹窗展示，高德定位SDK将不会工作
  static void updatePrivacyShow(bool hasContains, bool hasShow) {
    AMapFlutterLocation.updatePrivacyShow(hasContains, hasShow);
  }

  /// 设置是否已经取得用户同意，如果未取得用户同意，高德定位SDK将不会工作
  static void updatePrivacyAgree(bool hasAgree) {
    AMapFlutterLocation.updatePrivacyAgree(hasAgree);
  }

  // 初始化
  AMapLocationOption locationOption = new AMapLocationOption(
    // 是否需要地址信息，默认true
    needAddress: true,
    // 逆地理信息语言类型
    geoLanguage: GeoLanguage.ZH,
    // 是否单次定位 默认值：false
    onceLocation: true,
    // Android端定位模式, 只在Android系统上有效>
    locationMode: AMapLocationMode.Hight_Accuracy,
    // Android端定位间隔 2000毫秒
    locationInterval: 2000,
    // iOS端是否允许系统暂停定位
    pausesLocationUpdatesAutomatically: false,
    // iOS端期望的定位精度， 只在iOS端有效
    desiredAccuracy: DesiredAccuracy.Best,
  );

  /// 设置定位参数
  void setLocationOption(AMapFlutterLocation location) {
    location.setLocationOption(locationOption);
  }

  /// 开始定位
  Future<LocationInfo?> startLocation() async {
    if (await PermissionUtils().getLocation()) {
      if (await PermissionUtils().getLocationService()) {

        init();

        // 开启定位
        location.startLocation();

        return completer.future;
      }
    }
    return null;
  }

  /// 停止定位
  void stopLocation(AMapFlutterLocation location) {
    location.stopLocation();
  }

  ///销毁定位
  void destroy(AMapFlutterLocation location) {
    location.destroy();
  }

  ///定位结果返回
  Stream<Map<String, Object>> onLocationChanged(AMapFlutterLocation location) {
    return location.onLocationChanged();
  }
}


class LocationInfo {
  double longitude; // 经度
  double latitude; // 维度
  String address; // 详细地址

  LocationInfo({
    required this.latitude,
    required this.longitude,
    required this.address,
  });
}
